package com.jin.test.controller;

import com.jin.test.service.MergepdfTestService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

/**
 * @Package:com.jin.test.controller
 * @ClassName: MergepdfTestController
 * @Description: 项目中整合多个pdf合并为一个pdf
 * @Date: 2024/07/21 14:22
 * @Author: Jin
 */
@Log4j2
@RestController
@RequestMapping("/mergepdf")
@RequiredArgsConstructor
public class MergepdfTestController {

    //必须声明为final
    public final ResourceLoader resourceLoader;
    public final MergepdfTestService mergepdfTestService;

    @RequestMapping("/download")
    public void downloadFile(HttpServletResponse response) throws Exception {
        List<byte[]> finalList = Collections.synchronizedList(new ArrayList<>());

        ArrayList<String> fileNames = new ArrayList<>();
        Resource folderResource = resourceLoader.getResource("classpath:" + "mergepdfs");
        if (folderResource.exists()) {
            try (Stream<Path> files = Files.list(Paths.get(folderResource.getURI()))) {
                files.forEach(filePath ->
                        fileNames.add(filePath.toString())
                );
            }
            for (String fileNmae : fileNames) {
                File file = new File(fileNmae);
                FileInputStream fis = new FileInputStream(file);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int byteContent;
                while ((byteContent = fis.read()) != -1) {
                    bos.write(byteContent);
                }
                byte[] bytes = bos.toByteArray();
                finalList.add(bytes);
            }

            byte[] finalByte = mergepdfTestService.mergepdf(finalList);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(finalByte);
            outputStream.flush();
        } else {
            System.out.println("Folder not found: " + "mergepdfs");
        }
    }

}
